#!/usr/bin/env python
import subprocess
import sys
import os

def run_command(cmd, background=False):
    """运行命令"""
    try:
        print(f"执行命令: {cmd}")
        if background:
            proc = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
            return proc
        else:
            result = subprocess.run(cmd, shell=True, capture_output=True, text=True)
            print(f"输出: {result.stdout}")
            if result.stderr:
                print(f"错误: {result.stderr}")
            return result
    except Exception as e:
        print(f"命令执行失败: {e}")
        return None

def main():
    # 切换到项目目录
    os.chdir('/home/ubuntu/zlymes/mesmaster')
    
    # 激活conda环境
    conda_activate = "source ~/miniconda3/etc/profile.d/conda.sh && conda activate mes"
    
    # 测试Django
    print("=== 测试Django ===")
    django_test = f"{conda_activate} && python -c 'import django; print(django.VERSION)'"
    run_command(django_test)
    
    # 测试基础设置
    print("\n=== 测试基础设置 ===")
    settings_test = f"{conda_activate} && python manage.py check --settings=settings_mes_basic"
    run_command(settings_test)
    
    # 启动基础MES服务
    print("\n=== 启动基础MES服务 ===")
    start_basic = f"{conda_activate} && python manage.py runserver 0.0.0.0:8004 --settings=settings_mes_basic"
    proc1 = run_command(start_basic, background=True)
    
    if proc1:
        print(f"基础MES服务启动 PID: {proc1.pid}")
        print("基础MES服务: http://175.27.138.86:8004/")
        print("基础MES管理后台: http://175.27.138.86:8004/admin/")
    
    # 启动完整MES服务
    print("\n=== 启动完整MES服务 ===")
    start_full = f"{conda_activate} && python manage.py runserver 0.0.0.0:8005 --settings=settings_full_mes"
    proc2 = run_command(start_full, background=True)
    
    if proc2:
        print(f"完整MES服务启动 PID: {proc2.pid}")
        print("完整MES服务: http://175.27.138.86:8005/")
        print("完整MES管理后台: http://175.27.138.86:8005/admin/")
    
    # 启动Django管理服务
    print("\n=== 启动Django管理服务 ===")
    start_django = f"{conda_activate} && python manage.py runserver 0.0.0.0:8006 --settings=settings_django_with_mes"
    proc3 = run_command(start_django, background=True)
    
    if proc3:
        print(f"Django管理服务启动 PID: {proc3.pid}")
        print("Django管理服务: http://175.27.138.86:8006/admin/")
    
    print("\n=== 所有服务启动完成 ===")
    print("管理员账户: admin / admin123")
    print("按 Ctrl+C 停止服务")
    
    # 等待服务
    try:
        import time
        while True:
            time.sleep(1)
    except KeyboardInterrupt:
        print("\n正在停止服务...")
        if proc1:
            proc1.terminate()
        if proc2:
            proc2.terminate()
        if proc3:
            proc3.terminate()

if __name__ == "__main__":
    main() 